package cn._51doit.flink.day02.transformations;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.StreamFilter;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * StreamFilter底层实现
 */
public class FilterDemo4 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //spark
        //hive
        //hadoop
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);


        //输出以h开头的数据
//        FilterFunction<String> filterFunction = new FilterFunction<String>() {
//            @Override
//            public boolean filter(String line) throws Exception {
//                return line.startsWith("h");
//            }
//        };

        SingleOutputStreamOperator<String> filtered = lines.transform("MyFilter", TypeInformation.of(String.class), new MyStreamFilter());

        filtered.print();

        env.execute();
    }


    private static class MyStreamFilter extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> {

        @Override
        public void processElement(StreamRecord<String> element) throws Exception {
            String in = element.getValue();
            if (in.startsWith("h")) {
                //输出数据
                output.collect(element);
            }
        }
    }
}
